import json
import logging
import os
import traceback
from datetime import datetime
from django.db import transaction
from django.forms import model_to_dict
from django.http import JsonResponse, HttpResponse
from rest_framework import status
from Model.models import District, Subdistrict, Community, Address
from Model.modelsView import SubDistrictInfo, CommunityInfo, AddressInfo
from mgtServer.settings import MEDIA_ROOT
from tools.Tools import check_text, getCurrentUser, createHandleLog, readFile, getFileBytes

logger_info = logging.getLogger('info')
res = dict()


def importResource(request):
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            res_list = body.get('list')
            for i in res_list:
                district = checkDistrict(i)
                subDistrict = checkSubDistrict(i, district)
                community = checkCommunity(i, district, subDistrict)
                checkAddress(i, district, subDistrict, community)
                continue
            res['status'] = 200
            res['message'] = '导入成功!'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


def checkDistrict(record):
    dis = District.objects.filter(name=record['所属区域'], city=record['城市'])
    if dis.count() > 0:
        result = dis.last()
    else:
        district = District.objects.create()
        district.district_id = district.id
        district.name = record['所属区域']
        district.city = record['城市']
        district.save()
        result = district
    return result


def checkSubDistrict(record, district):
    sub = SubDistrictInfo.objects.filter(name=record['所属街道'], district_name=record['所属区域'], city=record['城市'])
    if sub.count() > 0:
        result = sub.last()
    else:
        subdistrict = Subdistrict.objects.create()
        subdistrict.subdistrict_id = subdistrict.id
        subdistrict.district_id = district.district_id
        subdistrict.name = record['所属街道']
        subdistrict.save()
        result = subdistrict
    return result


def checkCommunity(record, district, subDistrict):
    com = CommunityInfo.objects.filter(name=record['所属园区'], district_name=record['所属区域'],
                                       subdistrict_name=record['所属街道'], city=record['城市'])
    if com.count() > 0:
        result = com.last()
    else:
        community = Community.objects.create()
        community.community_id = community.id
        community.subdistrict_id = subDistrict.subdistrict_id
        community.district_id = district.district_id
        community.name = record['所属园区']
        community.save()
        result = community
    return result


def checkAddress(record, district, subDistrict, community):
    add = AddressInfo.objects.filter(name=record['蓝牌地址'], district_name=record['所属区域'], subdistrict_name=record['所属街道'],
                                     community_name=record['所属园区'], city=record['城市'])
    if add.count() > 0:
        result = add.last()
    else:
        address = Address.objects.create()
        address.address_id = address.id
        address.community_id = community.community_id
        address.subdistrict_id = subDistrict.subdistrict_id
        address.district_id = district.district_id
        address.name = record['蓝牌地址']
        address.save()
        result = address
    return result


def downloadResource(request):
    res.clear()
    try:
        if request.method == 'GET':
            out_stream = getFileBytes('zy.xls')
            response = HttpResponse(content_type='application/vnd.ms-excel', charset="UTF-8")
            response.write(out_stream)
            return response
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)
